package com.rui.common.interceptor;

import com.rui.common.annotation.PassToken;
import com.rui.common.exception.MyException;
import com.rui.common.util.HttpStatus;
import com.rui.common.util.RedisUtil;
import com.rui.common.util.SysConst;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * token校验拦截器
 *
 * @author xr
 * @email xr@qq.com
 * @date 2020-05-05 13:57:04
 */
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) {
        String token = request.getHeader(SysConst.TOKEN);
        /* 如果不是映射到方法直接通过 */
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        /* 检查是否有PassToken注释，有则跳过认证 */
        if (method.isAnnotationPresent(PassToken.class) && method.getAnnotation(PassToken.class).value()) {
            return true;
        }
        /* 执行认证 */
        if (StringUtils.isBlank(token)) {
            throw new MyException("token不存在", HttpStatus.UNAUTHORIZED.getCode());
        }
        String phone = redisUtil.get(token);
        if (StringUtils.isBlank(phone)) {
            throw new MyException(HttpStatus.UNAUTHORIZED);
        } else {
            String userStr = redisUtil.get(phone);
            if (StringUtils.isBlank(userStr)) {
                throw new MyException(HttpStatus.UNAUTHORIZED);
            } else {
                try {
//                    User user = JsonUtil.parse(userStr, User.class);
//                    if (user == null) {
//                        throw new MyException(HttpStatus.UNAUTHORIZED);
//                    }
                } catch (Exception e) {
                    throw new MyException(HttpStatus.UNAUTHORIZED);
                }
            }
        }

        return true;
    }

}
